package com.lgd.warehousemanagement.Activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.easy.view.dialog.EasyDialog;
import com.easy.view.utils.EasyUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lgd.warehousemanagement.Adapter.AbnormalOrderAdapter;
import com.lgd.warehousemanagement.Bean.SysUser;
import com.lgd.warehousemanagement.Bean.WorkHourCache;
import com.lgd.warehousemanagement.Bean.WorkHourStatistics;
import com.lgd.warehousemanagement.R;
import com.lgd.warehousemanagement.Utils.CacheDataManager;
import com.lgd.warehousemanagement.Utils.ScreenUtils;
import com.lgd.warehousemanagement.Utils.TimeUtils;
import com.lgd.warehousemanagement.Utils.ToastUtils;
import com.lgd.warehousemanagement.databinding.ActivityAbnormalOrderBinding;
import com.lgd.warehousemanagement.databinding.AfterWorkPopBinding;
import com.lgd.warehousemanagement.httpService.API;
import com.lgd.warehousemanagement.httpService.httpPort.IStringResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Method;
import java.util.List;

import android_serialport_api.SerialPortUtils;

/*
*   异常订单 列表界面
*/
public class AbnormalOrderActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "打卡异常列表界面：";
    ActivityAbnormalOrderBinding abnormalOrderBinding;
    private String scanResult;
    private Long userID;
    SerialPortUtils serialPortUtils;   // 串口对象
    String str_icCardNumber = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        abnormalOrderBinding = ActivityAbnormalOrderBinding.inflate(getLayoutInflater());
        setContentView(abnormalOrderBinding.getRoot());
        initView();
    }
    // 初始化控件事件
    public void initView(){

        EventBus.getDefault().register(AbnormalOrderActivity.this);    // 注册事件
        serialPortUtils = new SerialPortUtils();
        serialPortUtils.openSerialPort(4);        // 打开串口  /dev/ttyS0
        abnormalOrderBinding.layoutBack.setOnClickListener(this);
        closeInput(abnormalOrderBinding.etCardNumber);  //  关闭软键盘弹出
        clockRule();
        Intent intent = getIntent();
        str_icCardNumber = intent.getStringExtra("icCardNumber");
        if (str_icCardNumber != null && str_icCardNumber.length() > 0){
            setSeleceStaffInfo(str_icCardNumber,null);
        }
    }
    // 刷卡 事件 监听
    public void clockRule(){
        abnormalOrderBinding.etCardNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE ||
                        event.getAction() == KeyEvent.ACTION_DOWN &&
                                event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    scanResult = abnormalOrderBinding.etCardNumber.getText().toString();
                    if (scanResult.length() > 0){
                        if (scanResult.length() != 10){
                            abnormalOrderBinding.etCardNumber.setText("");
                            ToastUtils.warnShowLong(AbnormalOrderActivity.this,"卡片读取有误！请重新刷卡！");
                        }else{
                            abnormalOrderBinding.etCardNumber.setText(scanResult);
                            setSeleceStaffInfo(scanResult,null);
                        }
                    }
                    return true;
                }
                return false;
            }
        });
    }

    // 获取员工数据
    public void setSeleceStaffInfo(String icCard,String name){
        SysUser sysUser = new SysUser();
        if (icCard == null && name == null){
            seleceStaffInfo(sysUser);
            return;
        }
        if (icCard == null){
            sysUser.setNickName(name);
        }
        if (name == null){
            sysUser.setIcCard(icCard);
        }
        seleceStaffInfo(sysUser);
    }
    List<SysUser> sysUserList = null;
    //  获取 员工 信息
    public void seleceStaffInfo(SysUser sysUser){
        API.seleceStaffInfo(sysUser, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                AbnormalOrderActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        sysUserList = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<List<SysUser>>(){}.getType());
                        Log.d(TAG,"---员工信息-----"+sysUserList);
                        switch (sysUserList.size()){
                            case 0:
                                ToastUtils.warnShowLong(getApplicationContext(),"此卡为空卡，请联系管理员添加");
                                abnormalOrderBinding.etCardNumber.setText("");
                                break;
                            case 1:
                                abnormalOrderBinding.etCardNumber.setText("");
                                userID = sysUserList.get(0).getUserId();
                                abnormalOrderBinding.tvUserName.setText(sysUserList.get(0).getNickName());
                                ToastUtils.successShowLong(getApplicationContext(),"刷卡成功"+sysUserList.get(0).getNickName());
                                // 查询 异常 记录
                                WorkHourCache workHourCache = new WorkHourCache();
                                workHourCache.setUserid(userID);
                                selectAbnormalOrder(sysUserList,workHourCache);
                                break;
                            default:
                                break;
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {
                AbnormalOrderActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.warnShowLong(getApplicationContext(),"数据请求异常！！！");
                        abnormalOrderBinding.etCardNumber.setText("");
                    }
                });
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.layout_back:
                finish();
                break;
            default:
                break;
        }
    }
    //  重新获取 异常 工单数据
    public void setSelectAbnormalOrder (){
        WorkHourCache workHourCache = new WorkHourCache();
        workHourCache.setUserid(userID);
        selectAbnormalOrder(sysUserList,workHourCache);
    }

    //  异常订单 获取
    List<WorkHourCache> workHourCacheList = null;
    public void selectAbnormalOrder (List<SysUser> sysUserList, WorkHourCache workHourCache){
        API.selectAbnormalOrder(workHourCache, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                AbnormalOrderActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        workHourCacheList = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<List<WorkHourCache>>(){}.getType());
                        Log.d(TAG,"----异常----"+workHourCacheList);
                        if (workHourCacheList.size() > 0){
                            setAbnormalOrderListView(sysUserList,workHourCacheList);
                            abnormalOrderBinding.ivImg.setVisibility(View.GONE);
                            if (is_open_close && str_icCardNumber != null){
                                showDialog();
                                is_open_close = false;
                            }
                        }else {
                            abnormalOrderBinding.ivImg.setVisibility(View.VISIBLE);
                            setAbnormalOrderListView(sysUserList,null);   // 没有异常 工单
                            if (is_open_close && str_icCardNumber != null){
                                serialPortUtils.sendSerialPort("5501000000aa");
                                is_open_close = false;
                            }
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    //  设置 异常 工单 适配器
    AbnormalOrderAdapter abnormalOrderAdapter;
    public  void setAbnormalOrderListView (List<SysUser> sysUserList, List<WorkHourCache> workHourCacheList)
    {
        abnormalOrderAdapter = new AbnormalOrderAdapter(AbnormalOrderActivity.this, workHourCacheList);
        abnormalOrderBinding.lvAbnormalOrder.setAdapter(abnormalOrderAdapter);
        abnormalOrderBinding.lvAbnormalOrder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                WorkHourCache workHourCache = (WorkHourCache) abnormalOrderBinding.lvAbnormalOrder.getItemAtPosition(position);
                showAfterWorkPop(sysUserList, workHourCache,true);
            }
        });
    }
    // 下工 打卡弹窗
    PopupWindow after_work_pop;
    AfterWorkPopBinding afterWorkPopBinding;
    @SuppressLint("SetTextI18n")
    public void showAfterWorkPop(List<SysUser> sysUserList, WorkHourCache workHourCache, Boolean is_expired_not){
        AbnormalOrderActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                afterWorkPopBinding = AfterWorkPopBinding.inflate(getLayoutInflater());
                View after_work_view = afterWorkPopBinding.getRoot();
                int width = ScreenUtils.getWidth(AbnormalOrderActivity.this);
                after_work_pop = new PopupWindow
                        (after_work_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
                after_work_pop.setTouchable(true);
                after_work_pop.setFocusable(true);
                after_work_pop.setOutsideTouchable(true);
                after_work_pop.setBackgroundDrawable(new ColorDrawable(0x0000));
                after_work_pop.showAtLocation(AbnormalOrderActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
                setAfterWorkPopListener(workHourCache);
                afterWorkPopBinding.tvAfterName.setText(sysUserList.get(0).getNickName()+"(工号："+sysUserList.get(0).getIcCard()+")");
                afterWorkPopBinding.tvAfterGroup.setText(sysUserList.get(0).getDept().getDeptName());
                if (is_expired_not){    //   往期工单
                    afterWorkPopBinding.tvAfterTime.setText("请选择时间");
                    afterWorkPopBinding.tvAfterTime.setOnClickListener(v -> {
                        TimeUtils.timeSelect(AbnormalOrderActivity.this, workHourCache.getStarttime(), new TimeUtils.TimePickerCallback() {
                            @Override
                            public void onTimePicked(Boolean b, String formattedDateTime) {
                                // Log.d(TAG, "---时间选择----"+formattedDateTime+"--时间判断大小--"+b);
                                if (b){    // ture 代表 开始时间 > 结束时间
                                    afterWorkPopBinding.tvAfterTime.setText("请选择时间");
                                    afterWorkPopBinding.tvAfterDuration.setText(null);
                                    ToastUtils.warnShowLong(getApplicationContext(),"选择的时间 < 开始时间，请重新选择！");
                                }else {
                                    afterWorkPopBinding.tvAfterTime.setText(formattedDateTime);
                                    setDuration(workHourCache);  //  设置 工时
                                }
                            }
                        });
                    });
                }else {
                    afterWorkPopBinding.tvAfterTime.setText(TimeUtils.getCurrentDateTime());
                    setDuration(workHourCache);
                }
                afterWorkPopBinding.tvStartTime.setText(workHourCache.getStarttime());
            }
        });
    }

    // 下工 打卡弹窗监听
    public void setAfterWorkPopListener(WorkHourCache cache){
        setAlpha(0.2f);
        after_work_pop.setOnDismissListener(() -> {       //  监听 弹窗 关闭
            setAlpha(1f);
            abnormalOrderBinding.etCardNumber.setText("");
            setSelectAbnormalOrder ();
        });
        afterWorkPopBinding.ivAfterClose.setOnClickListener(new View.OnClickListener() {   // 手动关闭弹窗
            @Override
            public void onClick(View v) {
                after_work_pop.dismiss();
            }
        });
        afterWorkPopBinding.btAfterSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str_details = afterWorkPopBinding.etAfterDetails.getText().toString();
                String str_duration = afterWorkPopBinding.tvAfterDuration.getText().toString();
                String str_endTime = afterWorkPopBinding.tvAfterTime.getText().toString();
                if (str_endTime.equals("请选择时间")){
                    ToastUtils.warnShowLong(getApplicationContext(),"请选择时间");
                    return;
                }
                if (str_duration.isEmpty()){
                    ToastUtils.warnShowLong(getApplicationContext(),"工时异常，请重新选择时间！");
                    return;
                }
                if (str_details.isEmpty()){
                    ToastUtils.warnShowLong(getApplicationContext(),"请填写工作详情");
                    return;
                }
                // 提交数据  更新缓存表
                WorkHourCache workHourCache = new WorkHourCache();
                workHourCache.setProducedate(cache.getProducedate());
                workHourCache.setProjectid(cache.getProjectid());
                workHourCache.setDeptid(cache.getDeptid());
                workHourCache.setUserid(cache.getUserid());
                workHourCache.setStarttime(cache.getStarttime());
                workHourCache.setClocktype(cache.getClocktype());
                workHourCache.setEndtime(str_endTime);
                workHourCache.setWorkhourscacheid(cache.getWorkhourscacheid());
                workHourCache.setDuration(str_duration);
                workHourCache.setWorkhourid(cache.getWorkhourid());
                workHourCache.setIssueDetails(str_details);
                updateCache(workHourCache);

                afterWorkPopBinding.btAfterSubmit.setEnabled(false);
            }
        });
    }
    //  领料完成 提交
    Boolean is_open_close = false;   // false 关闭状态  true 打开状态
    public void updateCache(WorkHourCache workHourCache){
        is_open_close = false;
        API.updateCache(workHourCache, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                AbnormalOrderActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        afterWorkPopBinding.btAfterSubmit.setEnabled(true);
                        JSONObject j = JSONObject.parseObject(result);
                        long l = Long.parseLong(j.getString("code"));
                        String msg = j.getString("msg");
                        if (l == 200){
                            ToastUtils.successShowLong(getApplicationContext(),msg);
                            if (after_work_pop != null){
                                after_work_pop.dismiss();
                            }
                            is_open_close = true;
                        }else {
                            ToastUtils.warnShowLong(getApplicationContext(),msg);
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    private EasyDialog easyDialog;
    private void showDialog() {
        AbnormalOrderActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                EasyDialog.Builder builder = new EasyDialog.Builder(AbnormalOrderActivity.this)
                        .setContentView(R.layout.dialog_warm_tip)
                        .addCustomAnimation(Gravity.CENTER, true)       //添加自定义动画
                        .setCancelable(false)            //设置对话框外部可取消
                        .setText(R.id.tv_title, "温馨提示")            //设置标题
                        .setText(R.id.tv_content, "是否继续上报领料异常工单？")     //设置内容
                        .setText(R.id.tv_cancel, "不了，开门")
                        .setText(R.id.tv_confirm, "继续上报")
                        //设置弹窗宽高
                        .setWidthAndHeight(EasyUtils.dp2px(AbnormalOrderActivity.this, 400), LinearLayout.LayoutParams.WRAP_CONTENT)
                        .setOnClickListener(R.id.tv_cancel, v1 -> {     //添加点击事件  取消
                            easyDialog.dismiss();
                            serialPortUtils.sendSerialPort("5501000000aa");
                            startActivity(new Intent(AbnormalOrderActivity.this,MainActivity.class));
                        })
                        .setOnClickListener(R.id.tv_confirm, v2 -> {    //添加点击事件  确定
                            easyDialog.dismiss();
                        })
                        .setOnCancelListener(dialog -> {  //添加外部取消监听
//                            Log.d(TAG, " showDialog: 外部取消按钮点击事件 ");
                        })
                        .setOnDismissListener(dialog -> {     //弹窗消失监听
//                            Log.d(TAG, "showDialog: 提示弹窗 关闭 监听事件 ");
                        });
                //创建弹窗
                easyDialog = builder.create();
                //显示弹窗
                easyDialog.show();
            }
        });
    }

    //  设置 工时 时间上报实体类
    public void setDuration( WorkHourCache workHourCache){
        WorkHourStatistics w = new WorkHourStatistics();
        w.setStarttime(workHourCache.getStarttime());
        w.setEndtime(afterWorkPopBinding.tvAfterTime.getText().toString());
        w.setUserid(workHourCache.getUserid());
        calculateDuration(w);
    }
    //  根据开始 + 结束 + useid 查询工时
    String duration;
    public void calculateDuration(WorkHourStatistics w){
        duration = null;
        API.calculateDuration(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                AbnormalOrderActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        duration = jsonObject.getString("msg");     // 工时
                        afterWorkPopBinding.tvAfterDuration.setText(duration);
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    //接收主板回传信息
    @SuppressLint("ResourceType")
//    @Subscribe(threadMode = ThreadMode.MAIN)
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onEventMainThread(String msg) {
        AbnormalOrderActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.d("------接收到串口数据",msg);
                switch (msg) {
                    case "550100010000AA":
                        ToastUtils.successShowLong(getApplicationContext(),"开门成功!");
                        break;
                    default:
                        break;
                }
            }
        });
    }
    //    弹窗 遮罩层
    private void setAlpha(float f) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = f;
        getWindow().setAttributes(lp);
    }

    // 关闭软键盘弹出
    public void closeInput(EditText editText){
        //4.0以上
        try {
            Class<EditText> cls = EditText.class;
            Method setShowSoftInputOnFocus;
            setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            setShowSoftInputOnFocus.setAccessible(true);
            setShowSoftInputOnFocus.invoke(editText, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //  刷新 当前Activity
    private void reStartActivity() {
        Intent intent = getIntent();
        overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        finish();
        overridePendingTransition(0, 0);
        startActivity(intent);
    }
}